package code;

import java.util.Arrays;

public class Sort_Merge {
    public static void main(String[] args) {
        int a[] = new int[100];
        for (int i = 0; i < 100; i++) {
            a[i] = (int) (Math.random() * 100);
        }
        //int a[] = {3, 4, 2, 1, 7, 0};
        System.out.println("Old：" + Arrays.toString(a));
        sort_merge(a, 0, a.length - 1);
        System.out.println("New：" + Arrays.toString(a));
    }

    private static void sort_merge(int[] a, int low, int high) {
        int mid = (low + high) / 2;
        if (low < high) {
            sort_merge(a, low, mid);
            sort_merge(a, mid + 1, high);
            merge(a, low, mid, high);
        }
    }

    private static void merge(int[] a, int low, int mid, int high) {
        //现在已经将数组分成左右两个部分，现在合并这两个数组
        int i = low;
        int j = mid + 1;
        int temp[] = new int[high - low + 1];
        int k = 0; //填入temp数组的位置
        while (i <= mid && j <= high) {
            if (a[i] <= a[j]) {
                temp[k++] = a[i++];
            } else {
                temp[k++] = a[j++];
            }
        }
        //处理左右数组剩下的数据
        while (i <= mid) {
            temp[k++] = a[i++];
        }
        while (j <= high) {
            temp[k++] = a[j++];
        }
        //将temp拷贝到a中
        for (int x = 0; x < temp.length; x++) {
            a[x + low] = temp[x];
        }
    }
}
